<?php

namespace app;

use app\support\Printer;
use Respect\Validation\Exceptions\ValidationException;
use support\exception\BusinessException;
use support\exception\Handler;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
use Xin\VarDumper\VarDumperException;

class ExceptionHandler extends Handler
{
    /**
     * @param Request $request
     * @param Throwable $exception
     * @return Response
     */
    public function render(Request $request, Throwable $exception): Response
    {
        if ($exception instanceof VarDumperException) {
            return \response($exception->render(), 500);
        } elseif ($exception instanceof ValidationException) {
            return error($exception->getMessage())->withStatus(400);
        } elseif (($exception instanceof BusinessException) && ($response = $exception->render($request))) {
            return $response;
        }

        // 在控制台中打印错误信息
        Printer::error($exception->getMessage(), $exception->getTraceAsString());

        $code = $exception->getCode() ?: 500;
        $extend = [];
        $this->debug && $extend['traces'] = (string)$exception;
        return error(
            $this->debug ? $exception->getMessage() : 'Server internal error',
            $code,
            $extend
        )->withStatus(500);
//        return parent::render($request, $exception);
    }
}
